import random  # 添加这行

from flask import Blueprint, render_template, session, request, jsonify, redirect, url_for

from Models import Teacher, db, Classes, Student, Course

teacher_bp = Blueprint('teacher', __name__, url_prefix='/teacher')

@teacher_bp.before_request
def check_login():
    # 检查用户是否登录
    if session.get('user_type') !='teacher':
        return redirect(url_for('login'))
    if session.get('username') is None:
        return redirect(url_for('login'))  # 使用正确的登录端点


# 写路由
@teacher_bp.route('/')
def teacher_index():
    teacher = Teacher.query.filter_by(username=session['username']).first()
    return render_template('teacher/message.html', teacher=teacher)


@teacher_bp.route('/message/update/<string:id>', methods=['GET', 'POST'])
def update_message(id):
    current_user = Teacher.query.filter_by(teacher_no=id).first()
    print(current_user.username)
    # 获取表单数据
    email = request.form.get('email')
    telephone = request.form.get('telephone')
    address = request.form.get('address')
    current_password = request.form.get('current_password')
    new_password = request.form.get('new_password')
    # 验证当前密码（如果提供）
    if current_password and new_password:
        if not current_user.check_password(current_password):
            return jsonify({
                'status': 'error',
                'message': '当前密码不正确'
            }), 400
        # 更新密码
        current_user.password = new_password
    # 更新其他信息
    current_user.email = email
    current_user.telephone = telephone
    current_user.address = address
    # 提交到数据库
    db.session.commit()
    return jsonify({
        'status': 'success',
        'message': '个人信息更新成功'
    })


@teacher_bp.route('/student')
def teacher_student():
    teacher = Teacher.query.filter_by(username=session['username']).first()
    student_course_records = []
    # 遍历教师的所有课程
    for course in teacher.courses:
        # 遍历课程的所有选课记录（course_selections是CourseSelection对象列表）
        for selection in course.course_selections:
            # 通过selection.student获取单个学生对象（模型中backref='student'）
            student = selection.student
            if student:
                student_course_records.append({
                    'id': student.id,
                    'student_no': student.student_no,
                    'student_name': student.username,
                    'gender': student.gender,
                    'class': student.class_,  # 班级对象（若需班级名称，可改为student.class_.class_name）
                    'major': student.major,
                    'telephone': student.telephone,
                    'course_name': course.course_name,  # 直接从course对象获取课程信息
                    'course_code': course.course_code,
                    'selection_date': selection.selection_date.strftime('%Y-%m-%d'),
                    'status': selection.status
                })
    return render_template('teacher/student_manage.html', students=student_course_records)


@teacher_bp.route('/student/detail/<int:student_id>')
def student_detail(student_id):
    """获取学生详情接口"""
    # 查询学生对象，若不存在则返回 404
    student = Student.query.get_or_404(student_id)
    # 构造返回数据（包含学生基本信息和关联的班级、课程信息）
    student_data = {
        # 基本信息
        'student_no': student.student_no,  # 学号
        'username': student.username,  # 姓名
        'gender': student.gender,  # 性别
        'age': student.age,  # 年龄
        'telephone': student.telephone,  # 电话
        'address': student.address,  # 地址
        'status': student.status,  # 状态
        # 班级信息（通过关联模型获取）
        'class_id': student.class_id,  # 班级 ID（可选）
        'class_name': student.class_.class_name if student.class_ else None,  # 班级名称
        'major': student.major,  # 专业（可从学生模型或班级模型获取）
    }
    # print(student_data)
    return jsonify({
        'code': 200,
        'success': True,
        'message': '成功获取学生详情',
        'data': student_data
    })


@teacher_bp.route('/student/search', methods=['GET', 'POST'])
def student_search():
    """学生搜索接口（无分页，直接返回所有匹配结果）"""
    teacher = Teacher.query.filter_by(username=session['username']).first()
    keyword = request.args.get('keyword', '').strip()
    student_course_records = []
    # 遍历教师的所有课程
    for course in teacher.courses:
        # 遍历课程的所有选课记录（course_selections是CourseSelection对象列表）
        for selection in course.course_selections:
            # 通过selection.student获取单个学生对象（模型中backref='student'）
            student = selection.student
            if student:
                if student.username == keyword or student.student_no == keyword or student.class_.class_name == keyword:
                    student_course_records.append({
                        'id': student.id,
                        'student_no': student.student_no,
                        'student_name': student.username,
                        'gender': student.gender,
                        'class': student.class_,  # 班级对象（若需班级名称，可改为student.class_.class_name）
                        'major': student.major,
                        'telephone': student.telephone,
                        'course_name': course.course_name,  # 直接从course对象获取课程信息
                        'course_code': course.course_code,
                        'selection_date': selection.selection_date.strftime('%Y-%m-%d'),
                        'status': selection.status
                    })
    return render_template('teacher/student_manage.html', students=student_course_records, search_keyword=keyword)


@teacher_bp.route('/date')
def teacher_date():
    return render_template('teacher/date.html')


@teacher_bp.route('/class_message')
def teacher_class_message():
    teacher = Teacher.query.filter_by(username=session.get('username')).first_or_404()
    # 获取教师管理的班级列表
    classes = Classes.query.filter_by(advisor_id=teacher.id).first()
    students = classes.students
    attendance_rate = random.randint(50, 100)
    homework_rate = random.randint(50, 100)
    activity_rate = random.randint(50, 100)
    activity_level = random.randint(50, 100)
    return render_template('teacher/class_message.html', teacher=teacher, classes=classes, students=students,
                           attendance_rate=attendance_rate, homework_rate=homework_rate, activity_rate=activity_rate,
                           activity_level=activity_level)


@teacher_bp.route('/classes/<int:class_id>/update', methods=['POST'])
def update_class_info(class_id):
        class_obj = Classes.query.get_or_404(class_id)
        data = request.get_json()
                # 更新班级描述
        if 'description' in data:
            class_obj.description = data['description'].strip()

                # 更新班长（允许为null）
        if 'monitor_id' in data:
            if data['monitor_id'] is None:
                class_obj.monitor_id = None  # 取消班长
            else:
                student = Student.query.filter_by(
                            id=data['monitor_id'],
                            class_id=class_id
                        ).first()
                if not student:
                        return jsonify(success=False, message="学生不存在或不属于该班级"), 400
        class_obj.monitor_id = data['monitor_id']
        db.session.commit()
        return jsonify(success=True, message="修改成功"), 200


@teacher_bp.route('/course')
def teacher_course():
    teacher = Teacher.query.filter_by(username=session['username']).first()
    courses = teacher.courses
    classes_set=set()
    for course in courses:
        selections=course.course_selections
        for selection in selections:
            classes_set.add(selection.student)
    classes=""
    for i in classes_set:
        classes=classes+str(i.class_.class_name)+" "

    classes=classes.strip()
    return render_template('teacher/course_manage.html', courses=courses,classes=classes)


@teacher_bp.route('/course/<int:course_id>/detail', methods=['GET'])
def course_detail(course_id):
    """获取课程详情"""
    # 查询课程
    course = Course.query.get_or_404(course_id)
    course_data = {
            'course_id': course.id,
            'course_code': course.course_code,
            'course_name': course.course_name,
            'credit': course.credit,
            'department': course.department,
            'time': course.time,
            'location': course.location,
            'description': course.description,
        'teacher':session.get('username'),
        }

    return jsonify(course_data),200




@teacher_bp.route('/logout', methods=['POST'])
def logout():
    try:
        session.clear()  # 清除 Flask 原生会话（可选）
        return jsonify({'success': True, 'message': '退出登录成功'}), 200
    except Exception as e:
        return jsonify({'success': False, 'message': '退出登录失败'}), 500
